package io.github.lee.app.unsplash.ui.search

import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.app.unsplash.R
import io.github.lee.app.unsplash.repository.SearchRepository
import io.github.lee.app.unsplash.repository.domain.SearchKeyword
import io.github.lee.core.vm.BaseViewModel
import kotlinx.coroutines.Dispatchers
import java.util.Date
import javax.inject.Inject

@HiltViewModel
class SearchVM @Inject constructor(
    application: Application,
    private val repo: SearchRepository
) : BaseViewModel(application) {
    val searchKeyWord = ObservableField("")
    val showSearchClear = MutableLiveData(false)
    val cancelClicked = MutableLiveData(false)

    val hideKeyboard = MutableLiveData(false)

    //===Desc:======================================================================================
    fun searchInputChanged() {
        if (searchKeyWord.get().isNullOrEmpty()) {
            showSearchClear.postValue(false)
        } else {
            showSearchClear.postValue(true)
        }
    }

    fun clearSearchClick() {
        searchKeyWord.set("")
        hideKeyboard.postValue(false)
    }

    fun cancelClick() {
        cancelClicked.postValue(true)
    }


    fun queryCount(count: Int, block: (List<SearchKeyword>) -> Unit) {
        launch {
            repo.queryByCount(count).collect {
                block(it)
            }
        }
    }

    fun saveSearchKeyword() {
        val keyword = searchKeyWord.get()
        if (keyword.isNullOrEmpty()) {
            toast(getString(R.string.hint_search))
            return
        }
        launch(Dispatchers.IO) {
            val dbData = repo.queryByKeyword(keyword)
            if (null == dbData) {
                repo.insertKeyword(keyword)
            } else {
                dbData.updateTime = Date()
                repo.update(dbData)
            }
            hideKeyboard.postValue(true)
        }
    }

    fun clearAll() {
        launch(Dispatchers.IO) {
            repo.deleteAll()
        }
    }
}